标签: asp.net-web-api

Angular 2 http post null Web Api Core

我正在使用现有的Web Api(ASP.NET Core)在角度2中实现一个新的Web应用程序,但我遇到了HTTP Post的问题.在搜索了所有类型的信息之后,我仍然无法解决这个问题,我的Web API仍然从角度帖子接收空参数.

我需要看看这里有什么问题.这是我的Angular 2代码:

   posted(event) {
 @Injectable()
export class httpTestComponent {

constructor(public http: Http) {

};

posted(event) {
    var user: UserViewModel = {
        name: "angularUser",
        password: "pw",
        email: "angularMail"
    }
    let pedido = JSON.stringify(user);

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    this.http.post('http://localhost:10832/api/Account/Register', { pedido }, options)
        .map(this.extractData).catch(this.handleError).subscribe();
};
Run Code Online (Sandbox Code Playgroud)

视图模型:

export interface UserViewModel {
name: string,
password: string,
email: string,
Run Code Online (Sandbox Code Playgroud)

}

Web API:

 [HttpPost]
    [Route("Register")]
    public void Register([FromBody] UserRegisterViewModel …
Run Code Online (Sandbox Code Playgroud)

javascript asp.net http-post asp.net-web-api angular

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

ASP.NET Web API的Service Bus体系结构

我正在使用Telerik Platform开发移动应用程序.应用程序使用的服务是Azure上托管的ASP.NET Web API RESTful服务.我想通过添加服务总线为应用程序构建一些弹性,并且一直在寻找Azure服务总线,这似乎是我正在寻找的.

这对我来说还算新,我有几个问题.

  • Azure Service Bus是否可以用于返回数据的RESTful服务,或者只是一次性发送?
  • 对于简单的RESTful服务,还有Azure Service Bus可行的方式还是Azure存储队列?你什么时候使用一个与另一个?
  • 我何时使用队列与主题/订阅?

asp.net rest azure azureservicebus asp.net-web-api

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

如何解析包含C#list的Json WebApi响应

嗨,我有一个像json的回应

{"Status":"Success","Message":"Authentication successful","Data":{"Key":"sdsdIRs99Iebe6QHmawlBsCks9mqfUt6jKYNQ%2bW","UserId":"ddjjj8-11e6-637af7"}}

我怎么解析这个来读取响应.

我是这样做的:

private void POST(string url) 
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";

    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

    postData="{\"UserName\": \"abc\"," +"\"Password\": \"mypwd\"}";

    Byte[] byteArray = Encoding.UTF8.GetBytes(postData);

    request.ContentLength = byteArray.Length;
    request.ContentType = @"application/x-www-form-urlencoded";

    using (Stream dataStream = request.GetRequestStream())
    {
        dataStream.Write(byteArray, 0, byteArray.Length);
    }

    long length = 0;

    try 
    {
        using (HttpWebResponse response =  (HttpWebResponse)request.GetResponse())
        {
            length = response.ContentLength;
             using (var reader = new StreamReader(response.GetResponseStream()))
             {
                JavaScriptSerializer js = new JavaScriptSerializer();
                var objText = reader.ReadToEnd();

                string str= objText; …
Run Code Online (Sandbox Code Playgroud)

c# rest json json.net asp.net-web-api

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

如何从dotnet核心webapi下载ZipFile?

我试图从dotnet核心web api操作下载一个zip文件,但我无法使其工作.我尝试通过POSTMAN和我的Aurelia Http Fetch Client调用该操作.

我能够像我想要的那样创建ZipFile并将其存储在系统上,但无法修复它,因此它通过api返回zip文件.

用例:用户选择几个图片集并单击下载按钮.图片集的ID被发送到api并创建一个zipfile,其中包含用于保存图片的每个图片集的目录.该zipfile返回给用户,以便他/她可以将其存储在他们的系统上.

任何帮助,将不胜感激.

我的控制器动作

      /// <summary>
      /// Downloads a collection of picture collections and their pictures
      /// </summary>
      /// <param name="ids">The ids of the collections to download</param>
      /// <returns></returns>
      [HttpPost("download")]
      [ProducesResponseType(typeof(void), (int) HttpStatusCode.OK)]
      public async Task<IActionResult> Download([FromBody] IEnumerable<int> ids)
      {
           // Create new zipfile
           var zipFile = $"{_ApiSettings.Pictures.AbsolutePath}/collections_download_{Guid.NewGuid().ToString("N").Substring(0,5)}.zip";

           using (var repo = new PictureCollectionsRepository())
           using (var picturesRepo = new PicturesRepository())
           using (var archive = ZipFile.Open(zipFile, ZipArchiveMode.Create))
           {
                foreach (var id in ids)
                {
                     // Fetch …
Run Code Online (Sandbox Code Playgroud)

download zipfile asp.net-web-api .net-core aurelia-fetch-client

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

确保控制器在web api中有一个无参数的公共构造函数?

我正在努力解决使用untiy的依赖注入问题.我已根据此链接实施https://www.asp.net/web-api/overview/advanced/dependency-injection

但得到了这个错误:

{
  "Message": "An error has occurred.",
  "ExceptionMessage": "An error occurred when trying to create a controller of type 'WebAPIController'. Make sure that the controller has a parameterless public constructor.",
  "ExceptionType": "System.InvalidOperationException",
  "StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
  "InnerException": {
    "Message": "An error has occurred.",
    "ExceptionMessage": "Type 'Fairmoves.Controllers.WebAPIController' does not have a default constructor",
    "ExceptionType": "System.ArgumentException",
    "StackTrace": "   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc dependency-injection inversion-of-control unity-container asp.net-web-api

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

http客户端冻结在Windows窗体应用程序中

我正在关注这个例子,它可以在一个控制台应用程序中运行,但后来我在一个Windows窗体应用程序中尝试了它并且它会在命中行时await client.GetAsync("api/branches/1035") 如何不同?

控制台代码(这是有效的):

static void Main()
    {
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:49358/");

           client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("api/branches/1035");

            if (response.IsSuccessStatusCode)
            {
                branch branch = await response.Content.ReadAsAsync<branch>();
                Console.WriteLine("{0}\t${1}", branch.Id, branch.Color);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

当它击中时它会被冻结 await client.GetAsync("api/branches/1035")

private void button1_Click(object sender, EventArgs e)
    {
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:49358/");
            client.DefaultRequestHeaders.Accept.Clear(); …
Run Code Online (Sandbox Code Playgroud)

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

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

使用FOREACH麻烦AWAIT/ASYNC和WebApi

我有多种async方法从不同的基于OAuth的REST Api调用返回相同的类型.

如果我直接打电话给我,我可以收回数据:

//Call a specific provider
public async Task<List<Contacts>> Get()
{
    return await Providers.SpecificProvider.GetContacts();
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试遍历多个帐户,则对象将在AWAIT完成之前返回:

//Call all providers
public async Task<List<Contacts>> Get()
{
    return await Providers.GetContactsFromAllProviders();
}

public async Task<List<Contacts>> GetContactsFromAllProviders()
{
    var returnList = new List<Contacts>();
    //Providers inherits from List<>, so it can be enumerated to trigger
    //all objects in the collection
    foreach (var provider in Providers)
    {
        var con = await provider.GetContacts();
        returnList.Add(con);
    }
    return returnList;
}
Run Code Online (Sandbox Code Playgroud)

我是新手,async可能会遗漏一些简单的东西

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

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

测试Web API控制器?

我真的没有使用单元测试的经验,但是我试图在我的应用程序中实现一个非常简单的测试,并且不能让它运行.我有一个.NET Web API,带有我想测试的控制器.我在一个单独的项目中创建了以下测试类,并在其中引用了API:

[TestClass]
class TestWebhookControllers
{
    [TestMethod]
    public void TestTest_ShouldReturn201()
    {
        var controller = new TestWebhookController();
        controller.Request = new HttpRequestMessage();
        controller.Configuration = new HttpConfiguration();

        var result = controller.Get();

        Assert.AreEqual(result.StatusCode, HttpStatusCode.Continue);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我点击运行所有测试时,构建成功但没有其他事情发生.测试资源管理器为空.没有任何错误.我必须遗漏一些基本的东西.

.net c# unit-testing asp.net-web-api

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

我们应该在异常时发送什么响应代码 - WebAPI?

我在写Web-API方法.一种这样的方法类似于

public IHttpActionResult Post([FromBody]MyDTO)
{
   //validations 

   try
   {
      InsertInToDB(MyDTO.SomeField);
   }
   catch(Exception ex)
   {
      // Say some exception has occurred while inserting in to DB. For eg. SomeField is not a acceptable value.
      // What is the response that I should send to the API user ?
      // Notfound, BadRequest does not seem to be fit in this case.
   }

}
Run Code Online (Sandbox Code Playgroud)

注意:InsertIntoDB返回一个void

现在,如果在该方法中发生了一些异常HttpStatusCode,我应该向用户发送什么?

NotFound或者Badrequest回答似乎不适合这种情况.有任何想法吗 ?

.net c# exception asp.net-web-api asp.net-web-api2

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

如何在.net中处理Mandrill WebHooks

我是一名学生,正在尝试使用mandrill并且说实话,我不知道我在做什么.我能够在.net中使用mandrill发送电子邮件没有问题我现在要做的是使用webhooks来捕获当前的退回电子邮件,也许更多一次我完成了.

这是我到目前为止的代码(来自互联网)

public ActionResult HandleMandrillWebhook(FormCollection fc)
    {
        string json = fc["mandrill_events"];

        var events = JsonConvert.DeserializeObject<IEnumerable<Mandrill.MailEvent>>(json);
        foreach (var mailEvent in events)
        {
            var message = mailEvent.Msg;
            // ... Do stuff with email message here...
        }

        // MUST do this or Mandrill will not accept your webhook!
        return new HttpStatusCodeResult((int)HttpStatusCode.OK);
Run Code Online (Sandbox Code Playgroud)

然后我有了这个

public class MailEvent
{
    [JsonProperty(PropertyName = "ts")]
    public string TimeStamp { get; set; }

    [JsonProperty(PropertyName = "event")]
    public string Event { get; set; }

    [JsonProperty(PropertyName = "msg")]
    public Message Msg { …
Run Code Online (Sandbox Code Playgroud)

c# json webhooks asp.net-web-api mandrill

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