Quantcast
Channel: Web API
Viewing all 4850 articles
Browse latest View live

Consuming An XML Web Service

$
0
0

Hello, everyone.

I work for a small non-profit agency and we need to consume an older XML web service for one of our partners. Since I'm the only one around with any programming background, it's fallen to me to get this working.

I'm completely self taught and very new to both C# and ASP.NET.

This web service has a WSDL file which I've consumed with WCF. Everything went fine and I'm set up with a client.

However, I'm having trouble getting it working. I've put a method called "DownloadFile" in my HomeController and here is the code. Note that I've marked the client attributes with "null" to prevent the username, password and other information from being revealed.

        public ActionResult DownloadFile()
        {
            BasicHttpBinding binding = new BasicHttpBinding();
            binding.MaxReceivedMessageSize = 65536*2;
            var clientSCHED = new nullClient();
            var firstDate = DateTime.Today;
            var firstDateStr = firstDate.ToShortDateString();
            var lastDate = DateTime.Today;
            var lastDateStr = lastDate.ToShortDateString();
            var task1 = clientSCHED.AppointmentDataRawAsync("null", "null", "null",
                firstDateStr, lastDateStr, null, null);

            return DownloadFile(task1);

I know that it's wrong but I'm not certain why it's wrong. The client is supposed to return a list of appointments in XML format. Any assistance on this would be appreciated.


Web API program Publishing error

$
0
0

Hi All,

Please help...

I was trying to Publish same Web API program into the same server IIS new site with port (4442)

1. I am using File System Publish into C:\API2

2. In IIS I created a new Site and point that site into C:\API2, it automatically import into C:\inetput\wwwroot\....

3. I also have changed the Application Pool to .Net 4.0

4. When I Execute the new WebAPI through URL, it suppose return me ( ask to save as ) a .JSON file, but it always comes with a file without any extension ( size is ~ 5KB ).

And when I try to save it, it always return ERROR " couldn't be downloaded "

WebAPI issue

OWIN batch requests

$
0
0

How to configurate batch route in OWIN?

Before it I had Self-hosted WebApi and I did this way:

_webApiServer = new WebApiServer(..............
var config = _webApiServer.CreateDefaultConfig();
ConfigureBatchRoute(config);

private void ConfigureBatchRoute(HttpSelfHostConfiguration configuration)
{
const string batchRouteName = "WebApiBatch";
var batchRoute = configuration.Routes.MapHttpBatchRoute(batchRouteName, "api/$batch", new XxxxxHttpBatchHandler(_webApiServer.Server));
}
public class XxxxxHttpBatchHandler: DefaultHttpBatchHandler
{
public XxxxxHttpBatchHandler(WebApiServer webApiServer)
: base(webApiServer.Server)
public override async Task<IList<HttpRequestMessage>> ParseBatchRequestsAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
...........................
return requestMessages;
}
public HttpConfiguration CreateDefaultConfig()
{
var config = new HttpSelfHostConfiguration(host);
return config
}
public bool Start(HttpSelfHostConfiguration config)
{
Server = new HttpSelfHostServer(Configuration);
....
}
Now I do this way and it doesn't work

_webApiServer = new WebApiServer(..............
var config = _webApiServer.CreateDefaultConfig();
ConfigureBatchRoute(config);
private void ConfigureBatchRoute(HttpConfiguration configuration)
{
const string batchRouteName = "WebApiBatch";
var batchRoute = configuration.Routes.MapHttpBatchRoute(batchRouteName, "api/$batch", new XxxxxHttpBatchHandler(new HttpServer(configuration));

//Doesn't work too. Sample I took from web-api-2-recipes book var batchRoute = configuration.Routes.MapHttpBatchRoute(batchRouteName, "api/batch",new DefaultHttpBatchHandler(new HttpServer(configuration, new HttpRoutingDispatcher(configuration))));
}
public class XxxxxHttpBatchHandler: DefaultHttpBatchHandler
{
public XxxxxHttpBatchHandler(HttpServer httpServer)
: base(httpServer)
public override async Task<IList<HttpRequestMessage>> ParseBatchRequestsAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
...........................
return requestMessages;
}
public HttpConfiguration CreateDefaultConfig()
{
var httpConfiguration = new HttpConfiguration();
return config;
}
public bool Start(HttpConfiguration config)
{
_webApiService = WebApp.Start(
new StartOptions(_url), appBuilder => {appBuilder.UseWebApi(config);});
}

Message error: Invalid 'HttpContent' instance provided. It does not have a content type header starting with 'multipart/'.
Parameter name: content

Trying to prove out JWT with Web Api and x509 Certificates

$
0
0

Hi,

I am trying to use the Web Api and System.IdentityModel.Token.Jwt to do the following:

  • Create a JWT signed with an x509 Certificate.
  • Consume and validate the JWT signature.

I am new to the Web Api world so my terminology may be slightly off.  I'm getting errors on the validation of the token.

Here is the error I'm encountering trying to provide the SigningCredentials

{"IDX10618: AsymmetricSecurityKey.GetHashAlgorithmForSignature( 'HS256' ) threw an exception.\n AsymmetricSecurityKey: 'System.IdentityModel.Tokens.X509AsymmetricSecurityKey'\n SignatureAlgorithm: 'HS256', check to make sure the SignatureAlgorithm is supported.\nException: 'System.NotSupportedException: Crypto algorithm 'HS256' not supported in this context.\r\n   at System.IdentityModel.Tokens.X509AsymmetricSecurityKey.GetHashAlgorithmForSignature(String algorithm)\r\n   at System.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(AsymmetricSecurityKey key, String algorithm, Boolean willCreateSignatures)'."}

Here is the code to "try" to generate the JWT.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace WebApiClient1
{
    class resttest2
    {

        private String GetJWTToken()
        {
            
            //Claim
            var claimsIdentity = new ClaimsIdentity(new List<Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, "myemail@myprovider.com"),
                new Claim(ClaimTypes.Role, "Administrator"),
            }, "Custom");


            //create the token
            System.IdentityModel.Tokens.SecurityToken token;
            System.IdentityModel.Tokens.JwtSecurityTokenHandler handler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler();

            System.IdentityModel.Tokens.SecurityTokenDescriptor descriptor = new System.IdentityModel.Tokens.SecurityTokenDescriptor();
            descriptor.TokenIssuerName = "MikeTokenIss";
            descriptor.Subject = claimsIdentity;
            descriptor.SigningCredentials = GetSigningCredentials();
            descriptor.Lifetime = new System.IdentityModel.Protocols.WSTrust.Lifetime(DateTime.Now, null);

            token = handler.CreateToken(descriptor);
            var tokenstr = handler.WriteToken(token);
            return tokenstr;
        }

        private SigningCredentials GetSigningCredentials()
        {
            X509Certificate2 cert = new X509Certificate2("C:\\mike.pfx", "passwordforpfx");
            SigningCredentials creds = new X509SigningCredentials(cert, JwtAlgorithms.HMAC_SHA256, cert.GetKeyAlgorithm());
            return creds;
        }
        private AuthenticationHeaderValue GetAuthHeader()
        {
            AuthenticationHeaderValue authHeader = new AuthenticationHeaderValue("Bearer", GetJWTToken());
            return authHeader;
        }

        public class LoggingHandler : DelegatingHandler
        {
            public LoggingHandler(HttpMessageHandler innerHandler)
                : base(innerHandler)
            {
            }

            protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
            {
                Console.WriteLine("Request:");
                Console.WriteLine(request.ToString());
                if (request.Content != null)
                {
                    Console.WriteLine(await request.Content.ReadAsStringAsync());
                }
                Console.WriteLine();

                HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

                Console.WriteLine("Response:");
                Console.WriteLine(response.ToString());
                if (response.Content != null)
                {
                    Console.WriteLine(await response.Content.ReadAsStringAsync());
                }
                Console.WriteLine();

                return response;
            }
        }

        public async Task LocalRunAsync()
        {
            //using (var client = new System.Net.Http.HttpClient())
            using (
                var client = new HttpClient(new LoggingHandler(new HttpClientHandler()))
                )
            {
                Console.WriteLine("In RunAsync");
                client.BaseAddress = new Uri("http://localhost/RestTestMike20160825/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = GetAuthHeader();
                //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GetToken().ToString());
                Console.WriteLine("Added Headers");
                // HTTP GET

                System.Net.Http.HttpResponseMessage response = await client.GetAsync("api/products");
                Console.WriteLine("Called api/products/1");

                if (response.IsSuccessStatusCode)
                {
                    List<Product> output = default(List<Product>);


                    var jsonAsString = await response.Content.ReadAsStringAsync();
                    output = JsonConvert.DeserializeObject<List<Product>>(jsonAsString);
                    foreach (Product p in output)
                    {
                        Console.WriteLine("{0}\t${1}\t{2}", p.name, p.price, p.category);
                    }

                }
                else
                {
                    Console.WriteLine("Failure: " + response.ReasonPhrase);
                }

            }
        }


    }
}

Thanks in advance.

How to pass multiple parameter to web api action

$
0
0

here is the code

[AllowAnonymous]
        //http://localhost:29679/api/Customer/GetAll?CustomerID=001
        [HttpPost]
        [Route("GetAll")]
        public IHttpActionResult PostGetCustomer([FromUri]string CustomerID, [FromBody]ArrayList paramList)
        {
            Customer customers=new Customer();
            if (paramList.Count > 0)
            {
                Customer cus = Newtonsoft.Json.JsonConvert.DeserializeObject<Customer>(paramList[0].ToString());
                string teststringcus = CustomerID + " [ " + cus.name + " ] " + cus.ID;
                customers = cus;
                Order order = Newtonsoft.Json.JsonConvert.DeserializeObject<Order>(paramList[1].ToString());
            }

            Response responseclass = new Response(true, "SUCCESS", customers);
            return Content(HttpStatusCode.OK, responseclass, Configuration.Formatters.JsonFormatter);
        }

Client:

        using (var client = new System.Net.Http.HttpClient())
            {
                // HTTP POST
                var baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
                client.BaseAddress = new Uri(baseUrl);
                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                Customer customer = new Customer() { ID = "001", name = "testname 20 " };
                Order order = new Order() { ID = "001Oder" };
                ArrayList paramList = new ArrayList();
                paramList.Add(customer);
                paramList.Add(order);
                string contents = JsonConvert.SerializeObject(paramList);
                var response = client.PostAsync("/api/Customer/GetAll?CustomerID=001", new StringContent(contents, Encoding.UTF8, "application/json")).Result;
                string res = "";
                using (HttpContent content = response.Content)
                {
                    // ... Read the string.
                    Task<string> result = content.ReadAsStringAsync();
                    res = result.Result;
                }
            }

where arraylist is using which i do not want to post multiple class object to action.

so guide me with code how can i post multiple class object to action directly without any arraylist or tuple or viewmodel class.

Post Async with one or two string type parameter

$
0
0

see my action

        [HttpPost, Route("DeleteCustomer")]
        public HttpResponseMessage DeleteProduct(string customerID)
        {
            HttpResponseMessage response = null;
            Customer customer = repository.Get(customerID);
            if (customer == null)
            {
                var message = string.Format("No customer found by the ID {0}", customerID);
                HttpError err = new HttpError(message);
                response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
                response.ReasonPhrase = message;
            }
            else
            {
                if(repository.Remove(customerID))
                {
                    response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
                    response.ReasonPhrase = "Customer successfully deleted";
                }
                else
                {
                    var message = string.Format("Due to some error customer not removed");
                    HttpError err = new HttpError(message);
                    response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
                    response.ReasonPhrase = message;
                }
            }

            return response;
        }

now i am not being able to understand how to call it by httpclient. looking for sample code. thanks

interview question

$
0
0

i was asked in an interview the following question about webapi

Why we need webapi?

I told "the services that are created in webapi can be used across wide range of devices like laptop, desktop, tablet and mobiles."

Then the interviewer asked why it cannot be done using web services and wcf?

I don't know the answer.

Can anyone let me know the answer.

How to do the model validation in web api like asp.net MVC

$
0
0

i am looking for a small and complete web api code where model will be validated in action like asp.net MVC. please give me relevant article url or sample code.

thanks


How the data is posting in my sample code

$
0
0

please see the below code and tell me json or xml will be posting to web api action from client using httpclient.

public HttpResponseMessage PostProduct(Product p)
        {
            bool result = repository.AddProduct(p);
            HttpResponseMessage response;
            if(result)
            {
            response  = Request.CreateResponse(System.Net.HttpStatusCode.Created);
            }
            else
            {
                response = Request.CreateResponse(System.Net.HttpStatusCode.ExpectationFailed);
            }
            return response ; 
        }
Product p = new Product
           {
               ProductName = "DJ'S Pen",
               QuantityPerUnit = "20",
               Discontinued = true
           };
           HttpResponseMessage response = client.PostAsJsonAsync("products", p).Result;
           if (response.IsSuccessStatusCode)
           {
               Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
           }
           else
           {
               Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
           }

code taken from https://debugmode.net/2013/08/07/crud-operation-on-asp-net-web-api-from-net-client/

please see code and tell me xml or json will be posting to action from client side because no media type has been sent or no json has been generated for person class.

thanks

WebAPI: PostAsync with single or multiple query string does not work

$
0
0

see my sample web api action which take one string type parameter.

[HttpPost, Route("DeleteCustomer")]
public HttpResponseMessage DeleteProduct(string customerID)
{
    HttpResponseMessage response = null;
    Customer customer = repository.Get(customerID);
    if (customer == null)
    {
        var message = string.Format("No customer found by the ID {0}", customerID);
        HttpError err = new HttpError(message);
        response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
        response.ReasonPhrase = message;
    }
    else
    {
        if(repository.Remove(customerID))
        {
            response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
            response.ReasonPhrase = "Customer successfully deleted";
        }
        else
        {
            var message = string.Format("Due to some error customer not removed");
            HttpError err = new HttpError(message);
            response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
            response.ReasonPhrase = message;
        }
    }


    return response;
}

and calling like this below way with http client but not working and giving error Not found

private void btnDelete_Click(object sender, EventArgs e)
{
    var uri = new Uri(ConfigurationManager.AppSettings["baseAddress"] + "/api/customer/DeleteCustomer");

    var content = new FormUrlEncodedContent(new[] 
    {
        new KeyValuePair<string, string>("customerID", "CUS01")
    });

    try
    {
        using (var client = new HttpClient())
        {
            using (var response = client.PostAsync(uri, content).Result)
            {
                if (response.IsSuccessStatusCode)
                {
                    MessageBox.Show(response.ReasonPhrase);
                }
                else
                {
                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                    var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content.ReadAsStringAsync().Result);
                    MessageBox.Show(dict["Message"]);
                }
            }
        }
    }
    catch (HttpRequestException ex)
    {
        // catch any exception here
    }            

}

some one please see my code and tell me where i made the mistake in calling code ? thanks

How to transfer image binary data with base64 encoded from action to client and client to action

$
0
0

i am looking for a two small code which show how to transfer image binary data with base64 encoded from client to action and another code is opposite like transfer image binary data with base64 encoded from action to client.

why base64 encoded is used for transfer image binary data ?

thanks

The remote server returned an error: (401) Unauthorized. ( WEB API & WEB APP IS ON SAME SERVER)

$
0
0

I have WEB API & Web application both running on same server. I have enabled both for windows authentication. Web Application is consuming WEB API

code :

 

public static List<Course> GetCourses()

{

    List<Course> courseList = new List<Course>();
    webClient.Credentials = new NetworkCredential("xxx", "yyy","UAT");
    string courses = webClient.DownloadString("http://xx.yy.zz/api/Courses");

    dynamic dynObj = JsonConvert.DeserializeObject(courses);
        foreach (var data in dynObj)
           {
               Course course = new Course((string)data.CourseId, (string)data.CourseCode, (string)data.Description, (string)data.Name, (string)data.TypeCode);
               courseList.Add(course);
           }
     return Course.SortCoursesAlpha(courseList);

}

This works  locally when I tried to debug from my local machine where it works without popping username & password

. But after publishing to a server and when I tried to see if it works . It pops up the username & password and gives me :

Server Error in '/' Application.


The remote server returned an error: (401) Unauthorized.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Net.WebException: The remote server returned an error: (401) Unauthorized.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.


Stack Trace: 

[WebException: The remote server returned an error: (401) Unauthorized.]
   System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) +283
   System.Net.WebClient.DownloadString(Uri address) +100
   System.Net.WebClient.DownloadString(String address) +29
   StudentMailer.Mailer.ApiHandler.GetCourses() in c:\StudentMailer\trunk\StudentMailer\StudentMailer\Mailer\ApiHandler.cs:42
   StudentMailer._Default.Page_Load(Object sender, EventArgs e) in c:\StudentMailer\trunk\StudentMailer\StudentMailer\Default.aspx.cs:30
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +92
   System.Web.UI.Control.LoadRecursive() +54
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772

 


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34280

web application application pool details :

application pool : v4.0  Integrated LocalSystem  

WebAPI V1 4.0.30506 incorrect on Nuget? Really Version 4.0.20918

$
0
0

I'm looking for the last Webapi v1 for Framework 4.0, as per Nuget there should be a version 4.0.3056.

Downloading the 4.0.3 package and looking at the properties of the Dll's in the lib folder shows versions of 4.0.20918 which is from the prior release.

I binary compare shows them as identical. Seems the fact the entire 4.0.3 stack is is 4.0.2 (Core\Client\Http)

Anybody know how to get the DLL's or build them from source?

See Packages (rename to zip and compare)

https://www.nuget.org/packages/Microsoft.AspNet.WebApi.SelfHost/4.0.30506

 and

https://www.nuget.org/packages/Microsoft.AspNet.WebApi.SelfHost/4.0.20918

Kind Regards,

Mike

Claims aware application in VS 2015

Api related question

$
0
0

Hi,

1. My application uses Oauth 1.0 with bearer token based authorization. I would like to know is there any way that we can hide the url details on the help page based on companies using my API.

Assume i have 10 url's and for company A they should only see 3 and company B should only see 7. is there ay sample code to know how to achieve.

2) Is there any way to appy the same token based authorization for the help page?

Any sample code is most welcome.

Thanks in advance.


Authentication with web API

$
0
0

HI all

I have a web portal with database sql where there are account registered. I would to create a mobile app that must have somethings service of portal, so I would create API in my website and call it with my app. is it possible make a web api function to login and later call the other api function?

thanks in advice and sorry for my bad english!

How to use asp.net winapi with angular js?

$
0
0

Should I use SPA pattern? Or just simple web api page in asp.net mvc project? I do not need interaction with db. So I want to know in what folders I should put angular js files - in Content or Scripts? Or I need write it directly in view page? Do content type of $http.get request means? What port of localhost to use?  

Learning OData

$
0
0

Hello everyone and thanks for your help in advance.  I am learning to use OData api and realize one of the benefits of OData is the reusability factor.  I am refactoring some old code that queries a table tblClaims.  I have tow stored procedures, GetClaimDetailsByID and GetClaimDetailsByClaimNo.  Could someone walk me thorugh how to create a reusable OData api that preferably uses the two sprocs?  I have already built the class and context for a basic select * query.  Any help would be appreciated.

Could not reach controller in webapi project

$
0
0

Hi, I have a Web API project , I have implemented a controller, but when I ran application I could not reach the controller.

Here is the URI I tried to hit: http://localhost:8901/api/Foods

FoodsController, is which i have created.

Here is the response i am getting:

<div class="header">This XML file does not appear to have any style information associated with it. The document tree is shown below.</div> <div class="pretty-print"> <div class="collapsible" id="collapsible0"> <div class="expanded"> <div class="line"><Error></div><div class="collapsible-content"> <div class="collapsible" id="collapsible1"> <div class="expanded"> <div class="line"><Message></div> <div class="collapsible-content">No HTTP resource was found that matches the request URI 'http://localhost:8901/api/foods'.</div> <div class="line"></Message></div> </div> </div> <div class="collapsible" id="collapsible2"> <div class="expanded"> <div class="line"><MessageDetail></div><div class="collapsible-content">No type was found that matches the controller named 'foods'.</div> <div class="line"></MessageDetail></div> </div> </div> </div> <div class="line"></Error></div></div> </div> </div>

webapi + CORS: POST works, PUT does not

$
0
0

Hi,

I have a problem accessing a webapi-REST-service with CORS. What I've done so far:

  • installed Microsoft.AspNet.Cors V 5.2.3 via NuGet,
  • called config.EnableCors() in the "Register" method of WebApiConfig,
  • set the attribute [EnableCors("*", "*", "*")] on the controller.

A CORS-POST call (from an angular2-app) with headers "content-type: application/json" and "accept: application/json" succeeds. The corresponding Fiddler protocol lists the preflight-OPTIONS request from the browser (IE11) followed by the POST request.

If I issue a PUT request from the very same application, fiddler just lists the OPTIONS request with the servers answer "404 No action was found on the controller ... that matches the request". The PUT request uses the same headers as the POST request.

When I issue the PUT request from swagger/swashbuckle, everything works fine (just not being a CORS request). The controller is an ODataController.

Can anyone explain, what I'm doing wrong. If you need further info to solve this problem, please let me know.

Thanks in advance
Jürgen

Viewing all 4850 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>