I have a asp.net web app with some in page web service methods. It is not an asmx page, just Default.aspx. For example:
[WebMethod]
public static string SignUp(UserCredential userCredential)
{
}
I have no problem consuming this web service using jquery embeded in the Default.aspx page. Now I want to consume this web method in a console program for example. When I add the web reference to the console program, it said: The HTML document does not contain Web service discovery information.
How can I consume this in page web service?
Another option you have is to use the ASP.NET Web API to create your service methods and then consume them in a console application, like this:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
class Program
{
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:9000/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// Call Web API methods here
}
}
Read Calling a Web API From a .NET Client for a tutorial on consuming an ASP.NET Web API service from a C# console application.
You cannot consume that page method from outside of the page. You need a separate service for that.
You should do the following:
Create a separate WCF service project to hold the new service
Extract the guts of your page method into a similar service method in your new service project
Test the new service and make it work
In your ASP.NET project, use "Add Service Reference" to permit you to reference the new service
Call the new service from inside of the page method
Related
I built a REST API using ASP.NET Web API 2, so I could deliver data from a backend database to my applications running on any platform (mobile, web, desktop etc) However up until now, I simply call the website with the controller I need data from and that's it, it sends back the JSON string in the response.
But, the data is kind of special, and there is nothing to prevent another developer from simply calling the controllers and getting back the exact same data and building their own application around it.
My question is - is there anyway to restrict access to the API so that only my applications can get valid response from the server. (i.e. prevent other developers from using my REST API)
I already read these documentation Security, Authentication, and Authorization in ASP.NET Web API I'm just not sure which of these scenarios apply to me, or if any will do what I am asking.
EDIT - Another piece of info, my web service is running on Azure in case it is relevant.
Did you happen to check token based authentication?Please go through https://stackoverflow.com/a/38670221/4868839 and https://www.youtube.com/watch?v=rMA69bVv0U8 must be a good to start with.
there are different way to validate your web api.
Authentication Filters in ASP.NET Web API 2
using you can customise your authentication filter
you can refer sample Reference link
Token Based Authentication using ASP.NET Web API 2, Owin, and Identity
//App_Start/Startup class
public void ConfigureAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/v1/accesstoken"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(AppConfiguration.AccessTokenExpireDuration),
Provider = new SampleOAuthProvider() // class that override your method
};
// Token Generation
app.UseOAuthBearerTokens(OAuthServerOptions);
}
You can find reference from inherits Default implementation of IOAuthAuthorizationServerProvider used by Authorization
i hope it sholud helps you thanks.
We have to call a web service hosted by our client. We were able to add a web reference to our ASP.Net web application and use the web service. The client just sent us a text file and said we need to pass this as a cookie to get access to the web service. I ask for their help and they sent me this.
SoapHttpClientProtocol clientProxy = new T();
clientProxy.CookieContainer.Add(uri, cookie);
Is there a way to do this using a web reference? Or do I hav eto make a soap call?
The web reference you have generated should be derived from System.Web.Services.Protocols.SoapHttpClientProtocol (for details see this link). The ancestors of this class also provide a property named CookieContainer so that you can use the following code:
webRefInstance.CookieContainer.Add(uri, cookie);
Is there a good way to debug code from a console app to a web api project in VS2013? For example if I had some code such as:
Web API Controller
// GET api/values
public IEnumerable<string> Get()
{
return string [] { "value1, value2" };
}
Console Application
var client = new HttpClient();
var results = client.GetStringAsync("http://localhost:35690/api/values").Result;
I know I can use a browser or a tool like CURL. However, where this gets more complicated is handling a multipart form post for a file upload scenario I'd like to support.
If the WebAPI service is part of the same solution as the console application, you can simply set breakpoints wherever you wish and they are respected.
I am currently developing a WCF publish subscribe service. Is it possible for the publisher to be a asp.net application connecting to the service ? As I cant seem to find any information online about vb code for WCF.
EDIT
More details.
As my subscriber is a winform app, it is to subscribe to the WCF service using C# code and I am fine with that. the WCF Service is also coded in C# and I also have no problems with that. Normally the tutorials out in the web provides the code for a publisher to connect to the service and then call the publish code in console app or something. However all those is meant to be done in C#.
In my case, if i were to program the publisher code in a asp.net application. would it be possible?
EDIT : Codes Added
I am now currently using a C# mock publisher to post the data and the code are as follows
class Program : IPostingContractCallback
{
static void Main(string[] args)
{
InstanceContext site = new InstanceContext(new Program());
PostingContractClient client = new PostingContractClient(site);
client.PublishPost("testing");
Console.WriteLine();
Console.WriteLine("Press ENTER to shut down data source");
Console.ReadLine();
client.Close();
}
public void PostReceived(string postSampleData)
{
Console.WriteLine("PostChange(item {0})",postSampleData);
}
}
and for my asp.net webpage, I want all this to happen when I call this line of code
ElseIf Request.QueryString("action") = "postAlert" Then
How do I write the code as stated in above for vb? and do I just do as what I do in a C# project? adding the app.config file and the generatedProxy.cs?
You can do ASP.NET with VB.NET, so it's not a case of VB vs C#.
You could very easily write an ASP.NET application and have it connect to the publish service. The ASP.NET app would connect to the publishing service the same way a console app would (i.e., creating a new proxy/client and making calls to the service).
Updated
As Jon P said, use SVCUTIL and set the language to Visual Basic, like this:
SVCUTIL.EXE /language:vb (plus your other command line arguments)
ServiceModel Metadata Utility Tool (Svcutil.exe)
You'll want to add the <serviceModel> section to your Web.config, and generate the proxy in VB (using the /language:vb switch above).
Below is the VB version of the class you posted:
class Program Implements IPostingContractCallback
Shared Sub Main(string[] args)
Dim site As InstanceContext = New InstanceContext(New Program())
Dim client AS PostingContractClient = New PostingContractClient(site)
client.PublishPost("testing")
Console.WriteLine()
Console.WriteLine("Press ENTER to shut down data source")
Console.ReadLine()
client.Close()
End Sub
Public Sub PostReceived(ByVal postSampleData As String)
Console.WriteLine("PostChange(item {0})", postSampleData)
End Sub
End Class
Your ASP.NET app is acting as the publisher, but it's connecting to the publishing service (if I understand correctly), so all it's really doing is making a call to the service to publish the post.
The service itself should handle the callback and "publish" the event on the callback channel(s) for the subscriber.
So (without all the code for the various components I might be missing something - if I am, please let me know so I can update accordingly), all your ASP.NET app needs to do is:
Dim client As PostingContractClient = New PostingContractClient()
client.PublishPost("testing")
client.Close()
To reiterate (again, based on my understanding):
ASP.NET app calls the publishing service to publish the post.
The publishing service receives the post, and calls the callback method for all active subscribers.
Your subscribed client (the WinForm) receives the callback and processes it accordingly.
So for part 2, you might have something like:
public void PublishPost(string post)
{
// Do something with the post
callback.PostReceived(string postSampleData);
// callback is a callback channel of type IPostingContractCallback
// i.e:
// IPostingContractCallback calback = OperationContext.Current.GetCallbackChannel<IPostingContractCallback>();
}
The client(s) should then pick up the PostReceived "event" and do what their implementation of the callback interface specifies.
Use svc utuil to create your proxy class and set the language flag to vb
I have little Silverlight app that needs to make queries to server, is it possible to return objects to silverlight app or how can I communicate with server?
Use a WCF Service. As long as your objects are Serializable, the runtime will encode and decode them for you transparently.
A simple Silverlight-enabled WCF service looks something like this:
using System.ServiceModel;
using System.ServiceModel.Activation;
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
public class YourService
{
[OperationContract]
public string DoStuff(string arg)
{
return arg + "stuff";
}
}
You can replace "string" with your datatype by creating a [DataContract].
In my opinion it might be best to use web services to ship whatever is needed to your Silverlight application. I suggest that you use the WebClient class in combination with the URI class to obtain the data. Example:
Uri uri = new Uri(//the url of you webservice, UriKind.RelativeOrAbsolute);
Now create an instance of the WebClient class and add a callback to be called when the read from the web service is completed:
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(CallbackMethod);
wc.OpenReadAsync(uri);
When the data is retrieved from the server, the CallbackMethod is called. The method has an EventArgs object that contains a property called result. You can obtain your data using that property.
Silverlight doesnt need ASP at all to function, if you have a database on a seperate server check out WCF, and then get Silverlight to communicate with the WCF service and then the service with the database, if you want something more transparent, then try out WCF RIA services, this allows you to have a middle-tier approach to data access in silverlight