【问题标题】:"Cannot create an abstract class" error when converting API Method from .NET WebForms to .NET Web API将 API 方法从 .NET WebForms 转换为 .NET Web API 时出现“无法创建抽象类”错误
【发布时间】:2021-05-26 21:20:50
【问题描述】:

我想从我的旧 WebForms 应用程序创建一个新的 WEB API 应用程序。我将 POST 方法复制到控制器。我的 POST 方法基本上接收 JSON 作为参数并将 JSON 作为结果发送回来。这是控制器:

using Newtonsoft.Json;
using System.IO;
using System.ServiceModel;
using System.Web.Mvc;
using System.Xml;

namespace NewMvcApp.Controllers
{
    public class DataController : Controller
    {
        // GET: Data
        public ActionResult Index()
        {
            return View();
        }
        
        public class APIResponse
        {
            public string data { get; set; }
            public string infoMessage { get; set; }
        }

        [HttpPost, ActionName("request")]
        public System.ServiceModel.Channels.Message request(Stream json)
        {
            APIResponse result = new APIResponse();
            
            string message = new StreamReader(json).ReadToEnd();
            XmlDocument doc = JsonConvert.DeserializeXmlNode(message, "parameters");
            
            //do some logic and return 'result'
            
            string jsonSerialized = JsonConvert.SerializeObject(result);

            var iso = System.Text.Encoding.UTF8.GetBytes(jsonSerialized);

            MemoryStream memoryStream = new MemoryStream(iso);

            memoryStream.Position = 0;
            
            context.OutgoingResponse.Headers.Add("Cache-Control", "no-cache");
            context.OutgoingResponse.Headers.Remove("Set-Cookie");

            return context.CreateStreamResponse(memoryStream, "application/json; charset=utf-8");
        }
    }
}

我构建了这个应用程序并将其部署到了 Windows Server。但是,当我通过 POSTMAN 测试端点时

https://(mywebsite).com/Data/request

我总是收到这个错误:

Cannot create an abstract class.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.MissingMethodException: Cannot create an abstract class.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:
[MissingMethodException: Cannot create an abstract class.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +142
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +107
   System.Activator.CreateInstance(Type type) +13
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +271

[MissingMethodException: Cannot create an abstract class. Object type 'System.IO.Stream'.]
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +345
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +750
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +466
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +137
   System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__0(AsyncCallback asyncCallback, Object asyncState) +1082
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +163
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +463
   System.Web.Mvc.<>c.<BeginExecuteCore>b__152_0(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +48
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +68
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +163
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +787
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +163
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +630
   System.Web.Mvc.<>c.<BeginProcessRequest>b__20_0(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +99
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +68
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +163
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +544
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +970
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +75
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +158

我的 Global.asax.cs:

public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }

我的 POST 方法适用于我的 WebForms 应用程序。所以我可能错过了一些配置。我试图找到没有结果的解决方案。我该如何解决这个问题?

【问题讨论】:

    标签: c# asp.net asp.net-mvc visual-studio asp.net-web-api


    【解决方案1】:

    System.ServiceModel.Channels.Message 是一个抽象类。所以这个错误是有道理的。

    您不必回复消息。您可以返回您的对象。此外,您不必指定方法的 Stream 参数。

    基本上你可以这样做:

    public class APIRequest
    {
        public string parameter1 { get; set; }
        public int parameter2 { get; set; }
    }
    public class APIResponse
    {
        public string data { get; set; }
        public string infoMessage { get; set; }
    }
    

    在 DataController.cs 中

    [HttpPost, ActionName("request")]
    public APIResponse request(APIRequest req)
    {
        var response = new APIResponse
        {
           data = req.parameter2.ToString(),
           infoMessage = req.parameter1
        };
        return response;
    }
    

    请看this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-03
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      相关资源
      最近更新 更多