标签: asp.net-web-api

未经授权的webapi呼叫返回登录页面而不是401

如何配置我的mvc/webapi项目,以便从剃刀视图调用的webapi方法在未经授权时不返回登录页面?

它是一个MVC5应用程序,它也有通过javascript调用的WebApi控制器.

以下两种方法

[Route("api/home/LatestProblems")]      
[HttpGet()]
public List<vmLatestProblems> LatestProblems()
{
    // Something here
}

[Route("api/home/myLatestProblems")]
[HttpGet()]
[Authorize(Roles = "Member")]
public List<vmLatestProblems> mylatestproblems()
{
   // Something there
}
Run Code Online (Sandbox Code Playgroud)

通过以下角度代码调用:

angular.module('appWorship').controller('latest', 
    ['$scope', '$http', function ($scope,$http) {         
        var urlBase = baseurl + '/api/home/LatestProblems';
        $http.get(urlBase).success(function (data) {
            $scope.data = data;
        }).error(function (data) {
            console.log(data);
        });
        $http.get(baseurl + '/api/home/mylatestproblems')
          .success(function (data) {
            $scope.data2 = data;
        }).error(function (data) {
            console.log(data);
        });  
    }]
);
Run Code Online (Sandbox Code Playgroud)

所以我没有登录,第一个方法成功返回数据.第二种方法返回(在成功函数中)包含等效登录页面的数据.也就是说,如果你请求一个标有[授权]并且你没有登录的控制器动作,你会在mvc中获得什么.

我希望它返回401未授权,以便我可以根据用户是否登录显示不同的数据.理想情况下,如果用户已登录,我希望能够访问Controller的用户属性,以便我可以返回特定于该成员的数据.

更新:由于下面的建议似乎都不再适用(对Identity或WebAPI的更改)我在github上创建了一个原始示例,它应该说明问题.

c# asp.net-web-api owin asp.net-mvc-5 asp.net-identity

176
推荐指数
8
解决办法
8万
查看次数

抛出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万
查看次数

如何为C#MVC4 WebAPI应用程序全局记录所有异常?

背景

我正在为客户开发API服务层,并且我被要求在全局范围内捕获并记录所有错误.

因此,虽然通过使用ELMAH或通过向以下内容添加类似内容,可以轻松处理类似未知端点(或操作)的内容Global.asax:

protected void Application_Error()
{
     Exception unhandledException = Server.GetLastError();
     //do more stuff
}
Run Code Online (Sandbox Code Playgroud)

...不会记录与路由无关的未处理错误.例如:

public class ReportController : ApiController
{
    public int test()
    {
        var foo = Convert.ToInt32("a");//Will throw error but isn't logged!!
        return foo;
    }
}
Run Code Online (Sandbox Code Playgroud)

我还尝试[HandleError]通过注册此过滤器来全局设置该属性:

filters.Add(new HandleErrorAttribute());
Run Code Online (Sandbox Code Playgroud)

但这也不会记录所有错误.

问题/疑问

如何拦截错误,例如通过调用/test上面生成的错误,以便我可以记录它们?似乎这个答案应该是显而易见的,但我已经尝试了迄今为止我能想到的一切.

理想情况下,我想在错误记录中添加一些内容,例如请求用户的IP地址,日期,时间等.我还希望能够在遇到错误时自动通过电子邮件发送支持人员.所有这些我都可以做到,只要我能在它们发生时拦截这些错误!

解决!

感谢Darin Dimitrov,我接受了他的回答,我弄清楚了. 的WebAPI并没有以同样的方式作为一个普通MVC控制器处理错误.

这是有效的:

1)在命名空间中添加自定义过滤器:

public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is BusinessException)
        {
            throw new HttpResponseException(new …
Run Code Online (Sandbox Code Playgroud)

c# error-handling asp.net-web-api

170
推荐指数
3
解决办法
8万
查看次数

WebApi的{"消息":"发生错误"}在IIS7上,而不是在IIS Express中

我正在使用ASP.NET MVC 4 WebApi,并且在IIS Express上的本地计算机上运行它有很多乐趣.我已经将IIS Express配置为也为远程计算机提供服务,因此我公司的其他人正在使用我的计算机作为我们的网络服务器.

在确定这是一个不太理想的解决方案之后,我们决定在安装.NET 4.5之后将WebApi放在远程服务器上.当我使用fiddler并将POST发送到本地计算机上的控制器时,它会返回正确的响应,但是当我将域更改为运行IIS7的Web服务器时,同样的POST会返回一个神秘的

{"message":"发生了错误"}

信息.任何人都知道会发生什么事吗?

iis-7 asp.net-mvc-4 asp.net-web-api

169
推荐指数
6
解决办法
9万
查看次数

将内容放在HttpResponseMessage对象中?

几个月前,微软决定更改HttpResponseMessage类.之前,您可以简单地将数据类型传递给构造函数,然后返回包含该数据的消息,但不再是.

现在,您需要使用Content属性来设置消息的内容.问题是它是HttpContent类型,我似乎无法找到将字符串转换为HttpContent的方法.

有谁知道如何处理这个问题?非常感谢.

c# asp.net-mvc asp.net-web-api

167
推荐指数
7
解决办法
22万
查看次数

防止在Web API中序列化属性

我正在使用MVC 4 Web API和asp.net web forms 4.0来构建一个rest API.它工作得很好:

[HttpGet]
public HttpResponseMessage Me(string hash)
{
    HttpResponseMessage httpResponseMessage;
    List<Something> somethings = ...

    httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, 
                                 new { result = true, somethings = somethings });

    return httpResponseMessage;
}
Run Code Online (Sandbox Code Playgroud)

现在我需要阻止一些属性被序列化.我知道我可以在列表上使用一些LINQ并只获取我需要的属性,通常这是一个很好的方法,但在目前的情况下,something对象太复杂了,我需要在不同的方法中使用不同的属性集,所以它是在运行时,更容易标记要忽略的每个属性.

有没有办法做到这一点?

c# asp.net asp.net-mvc asp.net-web-api

165
推荐指数
10
解决办法
13万
查看次数

.NET HttpClient.如何POST字符串值?

如何使用C#和HttpClient创建以下POST请求: User-Agent:Fiddler内容类型:application/x-www-form-urlencoded主机:localhost:6740内容长度:6

我需要这样的WEB API服务请求:

[ActionName("exist")]
[System.Web.Mvc.HttpPost]
public bool CheckIfUserExist([FromBody] string login)
{           
    bool result = _membershipProvider.CheckIfExist(login);
    return result;
}
Run Code Online (Sandbox Code Playgroud)

c# asp.net-web-api dotnet-httpclient

165
推荐指数
4
解决办法
35万
查看次数

如何在ASP.NET WebAPI中返回文件(FileContentResult)

在常规的MVC控制器中,我们可以用a输出pdf FileContentResult.

public FileContentResult Test(TestViewModel vm)
{
    var stream = new MemoryStream();
    //... add content to the stream.

    return File(stream.GetBuffer(), "application/pdf", "test.pdf");
}
Run Code Online (Sandbox Code Playgroud)

但是我们怎样才能把它变成一个ApiController

[HttpPost]
public IHttpActionResult Test(TestViewModel vm)
{
     //...
     return Ok(pdfOutput);
}
Run Code Online (Sandbox Code Playgroud)

这是我尝试过但它似乎不起作用.

[HttpGet]
public IHttpActionResult Test()
{
    var stream = new MemoryStream();
    //...
    var content = new StreamContent(stream);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    content.Headers.ContentLength = stream.GetBuffer().Length;
    return Ok(content);            
}
Run Code Online (Sandbox Code Playgroud)

浏览器中显示的返回结果为:

{"Headers":[{"Key":"Content-Type","Value":["application/pdf"]},{"Key":"Content-Length","Value":["152844"]}]}
Run Code Online (Sandbox Code Playgroud)

在SO上有类似的帖子:从ASP.NET Web API中的控制器返回二进制文件 .它讨论输出现有文件.但我无法使用流.

有什么建议?

c# asp.net asp.net-mvc asp.net-web-api

158
推荐指数
6
解决办法
24万
查看次数

ASP.NET核心中基于令牌的认证

我正在使用ASP.NET Core应用程序.我正在尝试实现基于令牌的身份验证,但无法弄清楚如何在我的情况下使用新的安全系统.我经历了一些例子,但他们对我没什么帮助,他们使用的是cookie身份验证或外部身份验证(GitHub,Microsoft,Twitter).

我的场景是什么:angularjs应用程序应该请求/tokenurl传递用户名和密码.WebApi应授权用户并返回access_tokenangularjs app在以下请求中使用的内容.

我找到了很好的文章,关于在当前版本的ASP.NET中实现我所需要的 - 使用ASP.NET Web API 2,Owin和Identity进行基于令牌的身份验证.但对我来说,如何在ASP.NET Core中做同样的事情并不明显.

我的问题是:如何配置ASP.NET Core WebApi应用程序以使用基于令牌的身份验证?

c# authentication access-token asp.net-web-api asp.net-core

158
推荐指数
2
解决办法
7万
查看次数

ASP.NET Web API中具有多个GET方法的单个控制器

在Web API中,我有一类类似的结构:

public class SomeController : ApiController
{
    [WebGet(UriTemplate = "{itemSource}/Items")]
    public SomeValue GetItems(CustomParam parameter) { ... }

    [WebGet(UriTemplate = "{itemSource}/Items/{parent}")]
    public SomeValue GetChildItems(CustomParam parameter, SomeObject parent) { ... }
}
Run Code Online (Sandbox Code Playgroud)

由于我们可以映射单个方法,因此在正确的位置获得正确的请求非常简单.对于只有一个GET方法但也有Object参数的类似类,我成功使用了IActionValueBinder.但是,在上述情况下,我收到以下错误:

Multiple actions were found that match the request: 

SomeValue GetItems(CustomParam parameter) on type SomeType

SomeValue GetChildItems(CustomParam parameter, SomeObject parent) on type SomeType
Run Code Online (Sandbox Code Playgroud)

我试图通过重写ExecuteAsync方法来解决这个问题ApiController但到目前为止没有运气.关于这个问题的任何建议?

编辑:我忘了提到现在我试图在ASP.NET Web API上移动此代码,它具有不同的路由方法.问题是,如何使代码在ASP.NET Web API上运行?

c# asp.net-web-api

156
推荐指数
9
解决办法
20万
查看次数