取消/防止Dot Net Core中的路由导航

时间:2016-10-10 09:10:14

标签: c# api .net-core dotnet-httpclient

我在C#Dot Net Core中有一个典型的API,在收到ajax的{​​{1}}请求后会返回一个订单列表,如下所示:

$.getJSON(apiUrl)

我的控制器就像下面这样:

$.getJSON("api/Orders")
    .done(function (data) {
        // On success, 'data' contains a list of products.
        $.each(data, function (key, item) {
            // Add a list item for the product.
            $('<li>', { text: formatItem(item) }).appendTo($('#products'));
        });
    });

以上情况对我没问题。

我的问题是,如果用户在浏览器中输入了一个网址: public class OrdersController { [HttpGet("api/Orders")] public object Orders() { return new { . . }; } } 他将获得相同的输出,我想阻止它。

即。我需要仅允许通过http://localhost/api/Orders访问我的API,并且如果通过浏览器地址行中的ajax收到,则需要阻止(或取消或重定向)。

谢谢

2 个答案:

答案 0 :(得分:1)

您将无法禁止整个销售的导航请求。

您所能做的就是检查是否有特定的标题,表明它是一个AJAX请求。喜欢X-Requested-With。但任何基本的http客户端都允许人们添加它。

答案 1 :(得分:0)

感谢所有点击,我通过创建middleware解决了以下问题:

  1. 创建了一个文件夹Middleware
  2. 在这个新文件夹中,我创建了2个文件MiddleWalewareExtensions.csRequestHeaderMiddleware.cs

  3. MiddleWalewareExtensions.cs是定义我们所有中间件的那个,在这个例子中它只是一个,代码是:

    using Microsoft.AspNetCore.Builder;    // for IApplicationBuilder
    namespace myApp.Middleware
    {
       public static class MiddlewareExtensions  
    {
       public static IApplicationBuilder UseRequestHeaderMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<RequestHeaderMiddleware>();
    }
    ... here you can define others
    

    }   }

  4. RequestHeaderMiddleware是检查url是否包含单词api的中间件,仅当标头包含user-key并且此密钥为有效密钥时才会执行该密码,否则为错误被返回。 如果链接不包含api字,则在没有a的情况下执行 需要用户密钥。

     using Microsoft.AspNetCore.Http;
     using System.Threading.Tasks;
    
     namespace myApp.Middleware
     {
     public class RequestHeaderMiddleware  
     {
     private readonly RequestDelegate _next;
     public RequestHeaderMiddleware(RequestDelegate next)
     {
         _next = next;
     }
    
    public async Task Invoke(HttpContext context)
    {
        string url = context.Request.Path;
    
        if (url.Contains("api") && !context.Request.Headers.Keys.Contains("user-key"))
        {
            context.Response.StatusCode = 400; //Bad Request                
            await context.Response.WriteAsync("You need a user key to be able to access this API..");
            return;
        }
        else
            {
                if(context.Request.Headers["user-key"] != "28236d8ec201df516d0f6472d516d72d")
                {
                    context.Response.StatusCode = 401; //UnAuthorized
                    await context.Response.WriteAsync("Invalid User Key");
                    return;
                }
            }
    
        await _next.Invoke(context);
       }
      }
     } 
    
    1. Startup.cs文件中添加using myApp.Middleware;,然后:

      public void Configure(IApplicationBuilder app) 
      {
         app.UseRequestHeaderMiddleware();
         app.UseMvc(routes =>
         {
          routes.MapRoute(
              name: "default",
              template: "{controller=Home}/{action=Index}/{id?}");
         });
      
    2. 在JavaScript client app中,将所需的标头添加到xmlhttp,如:

         xmlhttp.setRequestHeader("user-key", "28236d8ec201df516d0f6472d516d72d");