标签: asp.net-web-api

在ASP.NET中,为什么DbSet.LastAsync()不存在?

我已经制作了一些代码来实现一些Web API.此API方法返回Foo Table的最后一条记录.

public class FooController : ApiController
{
    private FooContext db = new FooContext();

    // GET: api/Foo
    [ResponseType(typeof(Foo))]
    public async Task<IHttpActionResult> GetLastFoo()
    {
        Foo foo = await db.Foo.Last();
        if (foo == null)
        {
            return NotFound();
        }
        return Ok(foo);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想让这个API异步,但没有LastAsync()方法.为什么以及如何解决它?提前致谢.

asp.net async-await asp.net-web-api entity-framework-6

0
推荐指数
1
解决办法
232
查看次数

反序列化列表对象,返回null的属性

我正在尝试将数据发布到应该接受的API List<UpdatePointHistory>.列表的大小是正确的,但对象的属性是空白的.

public class UpdatePointHistory
{
    string Tree { get; set; }
    string FruitCount { get; set; }
    string Observations { get; set; }
    int PrivateId { get; set; }
}

public void Post([FromBody]List<UpdatePointHistory> updates)
{
    //Do some sort of auth for god sake
    Console.WriteLine("test");
}
Run Code Online (Sandbox Code Playgroud)

我发布的数据:

在此输入图像描述

从API返回的对象:

在此输入图像描述

c# deserialization asp.net-web-api frombodyattribute

0
推荐指数
1
解决办法
73
查看次数

NET Core Web API的IAuthorizationFilter中不接受AllowAnyonmous属性

我有一个用.net Core构建的新Web API,带有自定义授权过滤器。我需要绕过此过滤器进行少量操作,否则需要全局使用它。如何获取MyAuthFilter以兑现方法UserController.Post上的[Microsoft.AspNetCore.Authorization]属性?

授权过滤器:

public class MyAuthFilter : IAuthorizationFilter {
    public void OnAuthorization(AuthorizationFilterContext context) {
        //do some auth 
    }
}
Run Code Online (Sandbox Code Playgroud)

在Startup.cs中全局注册Auth过滤器:

public void ConfigureServices(IServiceCollection services) {
    services.AddMvc(options => {
        options.Filters.Add(new MyAuthFilter());
    });
}
Run Code Online (Sandbox Code Playgroud)

用户控制器上的属性修饰:

[Route("api/[controller]")]
[Authorize] //only want anonymous on single action within controller
public class UserController { 

    [HttpPost("login")]
    [AllowAnonymous] //this is not honored - MyAuthFilter.OnAuthorization is executed
        public JObject Post([FromBody] JObject userLogin) {

        }
}
Run Code Online (Sandbox Code Playgroud)

.net asp.net-web-api asp.net-core-webapi

0
推荐指数
2
解决办法
668
查看次数

Cookie可以从HttpResponseMessage中看到,但在Javascript中不可见

我有一个登录服务,当我登录时,它将用户登录信息传递给我的应用程序.这将在成功登录时调用我的应用程序的第一页.用户信息作为此请求中cookie的一部分传递.

我正在尝试使用以下代码在我的Web API请求中从请求中读取这些cookie.

 CookieHeaderValue getAccessUserInfo = request.Headers.GetCookies("GAUSERINFO").FirstOrDefault();

                if (getAccessUserInfo != null)
                {
                    userInfo = getAccessUserInfo["GAUSERINFO"].Values.Get("corporate_id");
                    Logger.Info(string.Format("User Cookie {0}", userInfo));
                    return userInfo;
                }
Run Code Online (Sandbox Code Playgroud)

但是,如果我试图从javascript或角度js读取相同的cookie,我无法在集合中看到该cookie.下面是我用来读取角度js中的cookie的代码.

console.log($document[0].cookie);
Run Code Online (Sandbox Code Playgroud)

这是我可以从结果中看到的cookie.我期待的cookie是GAUSERINFO以及下面的cookie.

在此输入图像描述

有没有办法从角度js或请求正文的至少传递读取这些cookie,以便我可以使用C#代码读取我的API中的cookie.

javascript c# cookies asp.net-web-api angularjs

0
推荐指数
1
解决办法
411
查看次数

IFormFile在执行异步操作时被释放

我有一个ASP.Net Core 2.0 webapi代码,如下所示

public class TestController : Controller
{
    private readonly ISampleRepository _sampleRepository = new SampleRepository();

    [HttpPost("{id}")]
    public async void Post([FromRoute]int id, IEnumerable<IFormFile> files, [FromForm] NotifyViewModel model)
    {
        // get data from DB using async
        var dbData = await _sampleRepository.GetAsync(id);

        //check if email alert is enabled 
        if(dbData.IsEmailEnabled)
        {
            //create MailMessage
            var mailMessage = new MailMessage() { 
                //options here 
                };

            foreach (var formFile in files)
            {
                mailMessage.Attachments.Add(new Attachment(formFile.OpenReadStream(), formFile.FileName, formFile.ContentType));
            }

            // send email
            _emailHelper.SendEmail(mailMessage);
        }
    }
}

public class …
Run Code Online (Sandbox Code Playgroud)

c# async-await asp.net-web-api asp.net-core

0
推荐指数
1
解决办法
689
查看次数

SelfHosting ApiController,如何返回错误

我使用这样的例子来创建一个自托管的API控制器.它可以HttpPostHttpGet一个Customer对象.

获得CustomerId 的(简化)函数是:

[RoutePrefix("test")]
public class MyTestController : ApiController
{
    [Route("getcustomer")]
    [HttpGet]
    public Customer GetCustomer(int customerId)
    {    // as a test: react as if this customer exists:
         return new Customer()
         {
              Id = customerId,
              Name = "John Doe",
         };     
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

这很好用.在我的客户端,我可以通过Id向该测试服务器询问客户,并且我获得具有预期数据的客户.

显然,调用函数知道如何将返回的Customer包装到HttpResponseMessage可以传输到我的客户端的对象(?)中.

下一步:如果找不到客户,则返回错误404.

[Route("getcustomer")]
[HttpGet]
public Customer GetCustomer(int customerId)
{    // as a test: only customer 1 exists
     if (customerId == 1)
     {
         return new Customer() …
Run Code Online (Sandbox Code Playgroud)

c# self-hosting http-status-code-404 asp.net-web-api owin

0
推荐指数
1
解决办法
35
查看次数

Angular 4等到http.get执行继续

我正在使用Ionic通过应用程序创建一个新的寄存器,并使用ASP.Net(C#)作为我的API。

我想检查输入模糊事件激活时用户是否存在。

问题是我的代码没有等到服务器返回值继续。我究竟做错了什么?有没有办法做到这一点?

这是我的API代码:

    [HttpGet]
    public JsonResult verifyEmail(string email)
    {
        var result = Domain.Repository.UserController.Find(email:email);
        if (result != null)
        {
            return Json(new { erro = true, message = "Email already registered!" }, JsonRequestBehavior.AllowGet);
        }
        else
        {
            return Json(new { erro=false,message = "Email is valid!" },JsonRequestBehavior.AllowGet);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我创建了一个提供HTTP请求的提供商(authProvider):

   getData(data,func)
    {
        return  new Promise( (resolve,reject)=>{
          this.http.get(apiUrl+func, {params:data})  
          .subscribe(
           res=>{

            resolve(res.json());
          },
          async (err)=>{
            reject(err);

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

这是我的register.ts代码:

  validate()
  {
     let validEmail;
     validEmail= this.checkEmail();// I WANT THAT the "validEmail" receives returned value …
Run Code Online (Sandbox Code Playgroud)

json promise asp.net-web-api ionic3 angular

0
推荐指数
1
解决办法
6872
查看次数

ASP.NET Core Web App-所有终结点均返回404

我正在Visual Studio 2017中的ASP.NET Core项目上工作,该项目设置为在IIS Express中运行。该项目是由其他同事启动的,我只是克隆了存储库,但是在我的机器上,所有API端点都返回404 Not Found。我尝试从Startup类中删除所有配置,仅保留Mvc功能,但这无济于事。

c# asp.net-web-api asp.net-core visual-studio-2017

0
推荐指数
1
解决办法
510
查看次数

如何在无视图的WebAPI ASP.NET Core应用程序中使用[Authorize]和antiforgery?

当我无法保证客户端将使用哪个平台时,我[Authorize]在严格(即View较少)的ASP.NET Core WebAPI项目中使用注释时遇到了问题.也就是说,应用程序需要是一个真正的API,不需要特定的平台来访问.

注意:当我说"严格的WebAPI"时,我的项目实际上是作为由...生成的MVC项目开始的.

dotnet new mvc --auth Individual
Run Code Online (Sandbox Code Playgroud)

...我立即从中删除了所有视图等,并更改了路由首选项以匹配WebAPI约定.


我在想什么

当我通过AJAX访问标准登录功能(在下面的粘贴中剥离到基本要素)时,我获得了一个JSON有效负载并返回了一个cookie.

[HttpPost("apiTest")]
[AllowAnonymous]
public async Task<IActionResult> ApiLoginTest([FromBody] LoginViewModel model, string returnUrl = null)
{
    object ret = new { Error = "Generic Error" };

    if (ModelState.IsValid)
    {
        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
        if (result.Succeeded)
            ret = new { Success = true };
        else
            ret = new { Error = "Invalid login attempt" };
    }

    return new ObjectResult(ret);
}
Run Code Online (Sandbox Code Playgroud)

成功时,返回类似于以下内容的cookie:

.AspNetCore.Identity.Application=CfDJ8Ge9E-[many characters …
Run Code Online (Sandbox Code Playgroud)

c# ajax antiforgerytoken asp.net-web-api asp.net-core-2.0

0
推荐指数
1
解决办法
1522
查看次数

Web API在响应中给出null

我开发了一个带有web api两个参数的日期时间(开始和结束),然后应该给出不同的记录.

public HttpResponseMessage GetMeterPing(DateTime start, DateTime end)
    {
        try
        {


            var startDateTime = start;
            var endDateTime = end;

            var result = medEntitites.tj_xhqd.Where(m => m.sjsj >= startDateTime && m.sjsj <= endDateTime)
                                             .OrderByDescending(o => o.sjsj)
                                             .Select(s => new { s.zdjh, s.sjsj, s.xhqd })
                                             .Distinct()
                                             .FirstOrDefault();                                             


            return Request.CreateResponse(HttpStatusCode.OK, new { data = result });


        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
        }
    }
Run Code Online (Sandbox Code Playgroud)

API网址: http://localhost:14909/api/meters/GetMeterPing/2018-04-28T00:00:00/2018-04-27T23:59:59

当我运行web-api它时,它给了我

{ "数据":空}

同时在调试时result也是如此null

任何帮助将受到高度赞赏

c# rest response asp.net-web-api

0
推荐指数
1
解决办法
292
查看次数