相关疑难解决方法(0)

抛出HttpResponseException还是返回Request.CreateErrorResponse?

在查看ASP.NET Web API中的文章异常处理之后,我对于何时抛出异常vs返回错误响应感到困惑.我还想知道当你的方法返回特定于域的模型而不是HttpResponseMessage... 时是否可以修改响应

所以,在这里回顾一下我的问题,然后是一些带有#s的代码:

问题

关于案例#1的问题

  1. 我应该总是使用HttpResponseMessage而不是具体的域模型,以便可以自定义消息吗?
  2. 如果要返回具体的域模型,是否可以自定义消息?

关于案例#2,3,4的问题

  1. 我应该抛出异常还是返回错误响应?如果答案是"它取决于",你能否提供关于何时使用一个与另一个的情况/例子.
  2. 投掷HttpResponseExceptionVS有Request.CreateErrorResponse什么区别?输出到客户端似乎相同......
  3. 我是否应始终使用HttpError"包装"错误中的响应消息(是否抛出异常或返回错误响应)?

案例样本

// CASE #1
public Customer Get(string id)
{
    var customer = _customerService.GetById(id);
    if (customer == null)
    {
        var notFoundResponse = new HttpResponseMessage(HttpStatusCode.NotFound);
        throw new HttpResponseException(notFoundResponse);
    }
    //var response = Request.CreateResponse(HttpStatusCode.OK, customer);
    //response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
    return customer;
}        

// CASE #2
public HttpResponseMessage Get(string id)
{
    var customer = _customerService.GetById(id);
    if (customer …
Run Code Online (Sandbox Code Playgroud)

c# exception-handling http-status-codes asp.net-web-api

171
推荐指数
5
解决办法
13万
查看次数

asp.net核心中的Request.CreateResponse

下面是我的代码(部分代码),我想将其迁移到asp.net核心.我的问题是"Request.CreateResponse"在下面的代码中不起作用.我谷歌很多,但无法找到任何解决方案.我该如何解决?包Microsoft.AspNet.WebApi.Core也无法正常工作.

    [HttpPost]
    public HttpResponseMessage AddBusinessUsersToBusinessUnit(MyObject request)
    {
        return Request.CreateResponse(HttpStatusCode.Unauthorized);
    }
Run Code Online (Sandbox Code Playgroud)

提前致谢.

asp.net asp.net-core

13
推荐指数
1
解决办法
3万
查看次数